package cn.seamus.marksman.processor.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.Assert;

import cn.seamus.marksman.common.Constants;
import cn.seamus.marksman.common.MarksmanException;

/**
 * 
 * 
 * <p>
 * 打开商品页，并加入购物车
 * </p>
 * 
 * @author zhengss
 * @version 0.0.1
 * @see
 */
public class GoodsPageProcessor extends AbstractProcessor {
    private static Log logger = LogFactory.getLog(GoodsPageProcessor.class);

    @Override
    protected Map<String, Object> prepareNext(Map<String, Object> params) throws MarksmanException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected ProcessResult read(Map<String, Object> requestParams) throws MarksmanException {
        logger.info("Goods page begin");
        Assert.notNull(requestParams);

        String goodsPageUrl = (String) requestParams.get(Constants.MAP_KEY_NEXT_PAGE);

        Assert.notNull(goodsPageUrl);
        Assert.isTrue(StringUtils.isNotBlank(goodsPageUrl));

        String quantity = (String) requestParams.get(Constants.MAP_KEY_QUANTITY);
        Assert.notNull(quantity);
        Assert.isTrue(StringUtils.isNotBlank(quantity));

        try {
            int num = Integer.valueOf(quantity);
            if (num <= 0) {
                throw new MarksmanException("Configuration error: wrong goods quantity. quantity=" + quantity);
            }
        } catch (NumberFormatException e) {
            throw new MarksmanException("Configuration error: wrong goods quantity. quantity=" + quantity);
        }

        URL goodsPageURL = null;

        try {
            goodsPageURL = new URL(goodsPageUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create goodsPageURL: goodsPageUrl=" + goodsPageUrl, e);
        }

        logger.info("URL= " + goodsPageURL.toString());
        logger.info("Connecting...");
        CloseableHttpResponse response = executeGet(goodsPageURL, null);

        ProcessResult result = new ProcessResult();
        Map<String, Object> resMap = new HashMap<String, Object>();
        result.setParams(resMap);
        String actionUrl = null;
        String actionMethod = null;
        String goodsId = null;
        try {

            String body = EntityUtils.toString(response.getEntity());

            Document doc = Jsoup.parse(body);

            Element inputForm = doc.getElementById("product-actions");
            actionUrl = inputForm.attr("action");
            actionMethod = inputForm.attr("method");
            Elements goodsIdSelected = doc.getElementById("product-select").select("option");

            goodsId = goodsIdSelected.attr("value"); // 347207639

            resMap.put(Constants.PARAM_KEY_ADDTOCART_ACTION_URL, actionUrl);
            resMap.put(Constants.PARAM_KEY_ADDTOCART_ACTION_METHOD, actionMethod);

            logger.info("actionUrl=" + actionUrl + ", method=" + actionMethod);

        } catch (IOException e) {
            throw new MarksmanException("Cannot parse  content", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        // 添加到购物车
        actionUrl = goodsPageURL.getProtocol() + "://" + goodsPageURL.getHost() + actionUrl;
        URL addtocartURL = null;
        try {
            addtocartURL = new URL(actionUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create addtocartURL: actionUrl=" + actionUrl, e);
        }

        // 购买数量

        Map<String, Object> reqParams = new HashMap<String, Object>();
        reqParams.put(Constants.REQ_PARAM_NAME_ADDTOCART_QUANTITY, quantity);
        reqParams.put(Constants.REQ_PARAM_NAME_ADDTOCART_ID, goodsId);

        if ("post".equalsIgnoreCase(actionMethod)) {
            response = executePost(addtocartURL, reqParams);
        } else {
            response = executeGet(addtocartURL, reqParams);
        }

        // 检查结果
        try {

            String body = EntityUtils.toString(response.getEntity());

            Document doc = Jsoup.parse(body);

        } catch (IOException e) {
            throw new MarksmanException("Cannot parse  content", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        logger.info("Goods page end.");
        return result;
    }

}
